package com.xlh.listener;

import com.xlh.pojo.courseTest.CourseTestPaper;
import com.xlh.service.courseTest.PaperService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.DelayQueue;

/**
 * @author zhr 2019/2/22
 */
@Component
public class EndCourseTestListener implements ApplicationListener<ContextRefreshedEvent> {
    private static final Logger LOGGER = LoggerFactory.getLogger(EndCourseTestListener.class);

    private static DelayQueue<EndCourseTestTask> delayQueue = new DelayQueue<>();

    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Autowired
    private PaperService paperService;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        if (event.getApplicationContext().getParent() == null) {
            // 启动时需要查询正在进行且未结束的考试，丢入到延时任务队列中
            List<CourseTestPaper> paperList = paperService.getTestingPaper();
            paperList.forEach(paper -> putTask(new EndCourseTestTask(paper.getId(), paper.getEndTime())));

            // 随后，启动一个线程，监控延时任务队列
            new Thread(() -> {
                while (true) {
                    try {
                        EndCourseTestTask task = delayQueue.take();
                        threadPoolTaskExecutor.execute(task);
                    } catch (Exception e) {
                        LOGGER.error(e.getMessage(), e);
                    }
                }
            }).start();
        }
    }

    public static void putTask(EndCourseTestTask task) {
        delayQueue.put(task);
    }
}
